﻿using beway.common;
using Beway.ValueAdded.Service;
using Beway.ValueAdded.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace Beway.ValueAdded.RechargeGateway.Controllers
{
    /// <summary>
    /// 黑龙江移动流量红包接口
    /// </summary>
    public class HLJMobileController:BaseController
    {
        RechargeServ rs = new RechargeServ();

        /// <summary>
        /// 应用key和密钥
        /// </summary>
        private static readonly string APPKEY = "fb7c7f7272a541f285abc8ae87e1c15d";
        private static readonly string APPSECRET = "10190c064cf84d018c25a9f07443df16";

        /// <summary>
        /// 认证接口地址
        /// </summary>
        private const string AUTHURL = "https://hl.4ggogo.com/web-in/auth.html";

        /// <summary>
        /// 充值接口地址
        /// </summary>
        private const string RECHARGEURL = "https://hl.4ggogo.com/web-in/boss/charge.html";


        public ActionResult Test() {
            
            string token = this.TokenContainer.Token;
            return Content(token);
        }

        #region Token容器
        /// <summary>
        /// token容器
        /// </summary>
        private static AuthToken _tokenContainer;

        /// <summary>
        /// Token容器，自动管理Token生命周期
        /// </summary>
        public AuthToken TokenContainer
        {
            get
            {
                if (_tokenContainer != null && _tokenContainer.ExpiredTime > System.DateTime.Now)
                {
                    return _tokenContainer;
                }
                else
                {
                    string dt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo);
                    string signHex = AuthToken.Sha256Hex(APPKEY + dt + APPSECRET);
                    string authReqXml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><Request><Datetime>{0}</Datetime><Authorization><AppKey>{1}</AppKey><Sign>{2}</Sign></Authorization></Request>", dt, APPKEY, signHex);
                   

                    HttpWebRequest HttpWebRequest = WebRequest.Create(AUTHURL) as HttpWebRequest;

                    HttpWebRequest.Method = "POST";
                    HttpWebRequest.ContentType = "application/xml";
                    string rspXml = Util.HttpHelper.HttpAction(HttpWebRequest, authReqXml);

                    if (!string.IsNullOrWhiteSpace(rspXml))
                    {
                        try
                        {
                            XmlDocument xml = new XmlDocument();
                            xml.LoadXml(rspXml);
                            _tokenContainer = new AuthToken()
                            {
                                CreatedTime = DateTime.Parse(xml.GetElementsByTagName("CreatedTime")[0].InnerText),
                                ExpiredTime = DateTime.Parse(xml.GetElementsByTagName("ExpiredTime")[0].InnerText),

                                Token = xml.GetElementsByTagName("Token")[0].InnerText
                            };
                        }
                        catch
                        {
                            _tokenContainer = null;
                        }
                    }
                    else
                    {
                        _tokenContainer = null;
                    }

                    return _tokenContainer;
                }
            }
        }
        #endregion

        #region 充值及回调接口
        /// <summary>
        /// 充值接口
        /// </summary>
        /// <param name="userId">充值平台分配的ID，每个系统都应有唯一的ID</param>
        /// <param name="mobile">手机号</param>
        /// <param name="proId">黑龙江移动提供的产品编码,43918为30元产品</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="sign">签名信息</param>
        /// <returns></returns>
        public ActionResult Charge(string proId)
        {
            string dt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo);
            string mobile = "13520357942";
            //string proId = "43918";//测试环境产品编码
            string orderNo = FileUtil.GetFileNameFromSystemAuto();

            Beway.ValueAdded.Model.Recharge rm = new Beway.ValueAdded.Model.Recharge()
            {
                UserID = 1,
                OrderAmount = 5,
                UserOrderNo = orderNo,//调用系统提供的订单号
                OrderID = orderNo,
                OrderTime = System.DateTime.Now,
                PayStatus = 1,//1为黑龙移动流量充值 
                RCTarget = mobile,
                RCType = 4, //流量包
                RechargeErrorReason = "",
                RechargeStatus = 0,
                RechargeAmount = 5
            };
            int rcid = rs.AddForUniqueOrderNo(rm);


            string reqXml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><Request><Datetime>{0}</Datetime><ChargeData><Mobile>{1}</Mobile><ProductId>{2}</ProductId><SerialNum>{3}</SerialNum></ChargeData></Request>", dt, mobile,proId,orderNo);

            HttpWebRequest webReq = WebRequest.Create(RECHARGEURL) as HttpWebRequest;
            webReq.Method = "POST";
            webReq.Headers.Add("4GGOGO-Auth-Token", this.TokenContainer.Token);
            webReq.Headers.Add("HTTP-X-4GGOGO-Signature", AuthToken.Sha256Hex(reqXml + APPSECRET));

            string rspXml = Util.HttpHelper.HttpAction(webReq, reqXml);

            return Content(rspXml);
        }


        /// <summary>
        /// 充值结果回调地址
        /// </summary>
        /// <returns></returns>
        public ActionResult ChargeCallback()
        {
            string rspBody = "<Response><Code>{0}</Code><Message>{1}</Message></Response>";
            var inputStream = Request.InputStream;
            if (inputStream != null)
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(inputStream);
                string orderNo = xml.GetElementsByTagName("SerialNum")[0].InnerText;
                string status = xml.GetElementsByTagName("Status")[0].InnerText;//3成功，4失败
                string mobile = xml.GetElementsByTagName("Mobile")[0].InnerText;
                string desc = xml.GetElementsByTagName("Description")[0].InnerText;
                string chargeTime = xml.GetElementsByTagName("ChargeTime")[0].InnerText;
                int ret_code = 0;
                if (status == "3")
                {
                    ret_code = 1;
                }
                else
                {
                    ret_code = 9;
                }

                int isok = rs.RechargeResultReceive(orderNo, ret_code, desc);                

                log.Info("充值结果异步通知" + orderNo + "," + status + "," + chargeTime + "," + desc);

                rspBody = string.Format(rspBody, "10000", "success");
            }
            else
            {
                rspBody = string.Format(rspBody, "10001", "callback xml is null");
            }
            return Content(rspBody);
        }
        #endregion

        /// <summary>
        /// 产品查询编码
        /// </summary>
        /// <returns></returns>
        public ActionResult Pro()
        {
            string reqUrl = "https://hl.4ggogo.com/web-in/products.html";

            HttpWebRequest webReq = WebRequest.Create(reqUrl) as HttpWebRequest;
            webReq.Method = "GET";
            webReq.Headers.Add("4GGOGO-Auth-Token", this.TokenContainer.Token);
            webReq.Headers.Add("HTTP-X-4GGOGO-Signature", AuthToken.Sha256Hex(APPSECRET));

            string rspXml = Util.HttpHelper.HttpAction(webReq);

            return Content(rspXml);
        }
    }

    /// <summary>
    /// 认证Token对象
    /// </summary>
    public class AuthToken
    {
        /// <summary>
        /// Sha256啥希，获得byte数组后再转为16进制字符
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="enc">编码格式</param>
        /// <returns></returns>
        public static string Sha256Hex(string str)
        {
            string ret="";
            if (string.IsNullOrWhiteSpace(str))
                return ret;

             
            Encoding  enc = System.Text.Encoding.UTF8;
            SHA256 sha256 = new SHA256Managed();
            var signByte = sha256.ComputeHash(enc.GetBytes(str));
            ret = beway.common.StringUtil.ByteToHex(signByte);
            return ret.ToLower();
        }
    
        /// <summary>
        /// 接口调用凭证
        /// </summary>
        public string Token{get;set;}

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedTime{get;set;}

        /// <summary>
        /// 接口调用凭证有效时间
        /// </summary>
        public DateTime ExpiredTime{get;set;}

        /// <summary>
        /// 指纹？？
        /// </summary>
        public string FingerPrint{get;set;}
    }
}